<template>
    <div>
        <el-collapse v-model="activeNames" accordion>
            <el-collapse-item title="查询条件(可点击收起)" name="1">
                <el-form :model="form" ref="searchForm" label-width="120px">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="厂商名" prop="name">
                                <el-input v-model="form.name" placeholder="请输入搜索的厂商名"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="厂编" prop="no">
                                <el-input v-model="form.no" placeholder="请输入搜索的厂编"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="状态" prop="status">
                                <el-select v-model="form.status" placeholder="请选择状态" clearable multiple style="width: 18rem">
                                    <el-option label="办理进场" :value="1"></el-option>
                                    <el-option label="已进场" :value="2"></el-option>
                                    <el-option label="已退场" :value="9"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-form-item label="到期日期范围" prop="endBegin">
                            <el-col :span="5">
                                <el-date-picker
                                    type="date"
                                    v-model="form.endBegin"
                                    format="yyyy 年 MM 月 dd 日"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择查询开始日期"
                                    :picker-options="pickerOptionsStart"
                                    @change="changeEnd"
                                ></el-date-picker>
                            </el-col>
                            <el-col class="line" :span="1" style="text-align: center">-</el-col>
                            <el-col :span="5">
                                <el-date-picker
                                    type="date"
                                    v-model="form.endEnd"
                                    format="yyyy 年 MM 月 dd 日"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择查询结束日期"
                                    :picker-options="pickerOptionsEnd"
                                    @change="changeStart"
                                ></el-date-picker>
                            </el-col>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-col :span="4" :offset="10">
                            <el-button type="primary" @click="searchCounter" :loading="loading">查询</el-button>
                            <el-button @click="reset('searchForm')">重置</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </el-collapse-item>
        </el-collapse>

        <el-table
            :data="tableData"
            stripe
            border
            :default-sort="{ prop: 'end', order: 'ascending' }"
            v-loading="loading"
            element-loading-text="拼命加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
        >
            <el-table-column type="expand" label="详情">
                <template slot-scope="props">
                    <el-form label-position="left" inline class="demo-table-expand" v-if="props.row.Device">
                        <el-form-item label="序列号:">
                            <span>{{ props.row.Device.serial }}</span>
                        </el-form-item>
                        <el-form-item label="设备名:">
                            <span>{{ props.row.Device.name }}</span>
                        </el-form-item>
                        <el-form-item label="型号:">
                            <span>{{ props.row.Device.model }}</span>
                        </el-form-item>
                    </el-form>
                    <span v-else>没有分配磅秤</span>
                </template>
            </el-table-column>
            <el-table-column type="index" label="序号">
                <template slot-scope="scope">
                    <span>{{ (form.page - 1) * form.pageSize + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="专柜名" sortable></el-table-column>
            <el-table-column prop="no" label="厂编" sortable></el-table-column>
            <el-table-column prop="status" label="状态" sortable>
                <template slot-scope="scope">
                    <span v-if="scope.row.status === 1" style="color: orange">办理进场</span>
                    <span v-if="scope.row.status === 2" style="color: green">已进场</span>
                    <span v-if="scope.row.status === 9" style="color: red">已退场</span>
                </template>
            </el-table-column>
            <el-table-column prop="begin" label="进场日期" sortable></el-table-column>
            <el-table-column prop="end" label="到期日期" sortable></el-table-column>
            <el-table-column prop="out" label="退场日期" sortable></el-table-column>
            <el-table-column prop="remark" label="备注" width="200" sortable></el-table-column>
            <el-table-column label="操作" fixed="right" width="300">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="primary"
                        @click="$router.push({ name: 'counterEdit', params: { id: scope.row.id } })"
                        v-if="(role === 'AD' && scope.row.status === 1) || (role === 'EDP' && scope.row.status === 2)"
                    >编辑</el-button>
                    <el-button size="mini" type="primary" @click="showDeviceList(scope.row)" v-if="scope.row.status === 1 && role === 'EDP'">分配磅秤</el-button>
                    <el-button size="mini" type="primary" @click="ShowRenewalSubmit(scope.row)" v-if="scope.row.status === 2 && role === 'AD'">续租</el-button>
                    <el-button
                        size="mini"
                        type="primary"
                        @click="$router.push({ name: 'renewal', params: { id: scope.row.id, name: scope.row.name } })"
                        v-if="scope.row.status === 2 || scope.row.status === 9"
                    >续租记录</el-button>
                    <el-button size="mini" type="danger" @click="updateStatus9(scope.row)" v-if="scope.row.status === 2 && role === 'EDP'">退场</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-row type="flex" justify="space-between" :gutter="20" style="padding: 10px 0">
            <el-col :span="4">
                <el-button @click="$router.push({ name: 'counterCreat' })" type="primary" v-if="role === 'AD'">新专柜入场</el-button>
            </el-col>
            <el-col :span="20">
                <el-pagination
                    background
                    style="float: right"
                    layout="prev, pager, next, sizes, total, jumper"
                    :page-sizes="[1, 5, 10, 15, 20]"
                    :page-size="form.pageSize"
                    :current-page="form.page"
                    :total="total"
                    @current-change="pageChange"
                    @size-change="sizeChange"
                ></el-pagination>
            </el-col>
        </el-row>

        <el-dialog :title="`${title} 续租`" :visible.sync="renewalFormVisible" :close-on-click-modal="false">
            <el-form :model="renewalForm" ref="renewalForm" label-width="130px">
                <el-form-item
                    label="续租(月)"
                    prop="month"
                    :rules="[
                        { required: true, message: '请输入续租期限', trigger: 'blur' },
                        { type: 'integer', min: 1, max: 120, message: '续租期限必须在 1 至 120 之间', trigger: 'blur' }
                    ]"
                >
                    <el-input-number v-model="renewalForm.month" controls-position="right" placeholder="请输入续租期限" :min="1" :max="120"></el-input-number>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="() => (renewalFormVisible = false)">取 消</el-button>
                <el-button type="primary" @click="renewalSubmit('renewalForm')">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="分配磅秤" :visible.sync="deviceListVisible" :close-on-click-modal="false">
            <el-table
                :data="deviceList"
                highlight-current-row
                @current-change="row => (device_id = row.id)"
                border
                style="width: 100%; margin-top: 15px"
                :default-sort="{ prop: 'name', order: 'ascending' }"
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
            >
                <el-table-column label width="35">
                    <template slot-scope="scope">
                        <el-radio v-model="device_id" :label="scope.row.id">{{ '' }}</el-radio>
                    </template>
                </el-table-column>
                <el-table-column prop="serial" label="序列号" sortable></el-table-column>
                <el-table-column prop="model" label="型号" sortable></el-table-column>
                <el-table-column prop="name" label="设备名" sortable></el-table-column>
                <el-table-column prop="remark" label="备注" sortable></el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button @click="() => (deviceListVisible = false)">取 消</el-button>
                <el-button type="primary" @click="distribute" :disabled="!device_id">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="退场" :visible.sync="exitVisible" :close-on-click-modal="false">
            <el-form label-width="80px">
                <el-form-item label="备注">
                    <el-input v-model="remark" placeholder="请输入备注, 是否有损坏需要会计扣款" clearable></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="() => (exitVisible = false)">取 消</el-button>
                <el-button type="primary" @click="exit">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import dayjs from 'dayjs'
import qs from 'qs'

export default {
    name: 'counterList',
    data() {
        return {
            loading: false,
            activeNames: '1',
            renewalFormVisible: false,
            tableData: [],
            form: {
                page: 1,
                pageSize: 10,
                name: null,
                no: null,
                status: [1, 2],
                endBegin: null,
                endEnd: null
            },
            id: null,
            title: '',
            renewalForm: {
                month: 1
            },
            total: null,
            deviceListVisible: false,
            deviceList: [],
            device_id: null,
            counter_id: null,
            pickerOptionsStart: {},
            pickerOptionsEnd: {},
            exitVisible: false,
            remark: null
        }
    },
    computed: {
        role() {
            return this.$store.getters.user.role
        }
    },
    methods: {
        reset(formName) {
            this.$refs[formName].resetFields()
        },
        async searchCounter() {
            sessionStorage.setItem('counterList', JSON.stringify(this.form))
            this.loading = true
            const res = await this.$http.get('/counterList', {
                params: this.form,
                paramsSerializer: params => {
                    return qs.stringify(params, { arrayFormat: 'indices' })
                }
            })
            if (res && res.code === 0) {
                // this.total = res.returnObject.count
                // this.tableData = res.returnObject.rows
                ;({ count: this.total, rows: this.tableData } = res.returnObject)
            }
            this.loading = false
        },
        pageChange(value) {
            this.form.page = value
            this.searchCounter()
        },
        sizeChange(value) {
            this.form.pageSize = value
            this.searchCounter()
        },
        ShowRenewalSubmit(row) {
            this.id = row.id
            this.renewalFormVisible = true
            this.title = `厂编:${row.no} 厂商名:${row.name}`
        },
        renewalSubmit(formName) {
            this.$refs[formName].validate(async valid => {
                if (!valid) return false
                const res = await this.$http.post('/renewal', {
                    counter_id: this.id,
                    month: this.renewalForm.month
                })
                if (res && res.code === 0) {
                    this.$message.success('保存成功')
                    const counter = this.tableData.find(item => item.id === this.id)
                    this.$set(
                        counter,
                        'end',
                        dayjs(counter.end)
                            .add(this.renewalForm.month, 'month')
                            .format('YYYY-MM-DD')
                    )
                }
                this.renewalFormVisible = false
            })
        },
        async showDeviceList(row) {
            this.device_id = null
            this.counter_id = row.id
            this.loading = true
            const res = await this.$http.get('/deviceListFree')
            if (res && res.code === 0) {
                this.deviceList = res.returnObject
            }
            this.loading = false
            this.deviceListVisible = true
        },
        async distribute() {
            const res = await this.$http.put(`/counterDistribute/${this.counter_id}`, { device_id: this.device_id })
            if (res && res.code === 0) {
                const counter = this.tableData.find(item => item.id === this.counter_id)
                this.$set(counter, 'Device', this.deviceList.find(item => item.id === this.device_id))
                this.$set(counter, 'status', 2)
                this.$message.success('修改成功')
            }
            this.deviceListVisible = false
        },
        changeStart() {
            this.pickerOptionsStart = Object.assign({}, this.pickerOptionsStart, {
                disabledDate: time => {
                    return this.form.endEnd ? time.getTime() > new Date(this.form.endEnd) : null
                }
            })
        },
        changeEnd() {
            this.pickerOptionsEnd = Object.assign({}, this.pickerOptionsEnd, {
                disabledDate: time => {
                    return time.getTime() < new Date(this.form.endBegin)
                }
            })
        },
        updateStatus9(row) {
            this.counter_id = row.id
            this.exitVisible = true
        },
        async exit() {
            const res = await this.$http.put(`/counterExit/${this.counter_id}`, { remark: this.remark })
            if (res && res.code === 0) {
                const counter = this.tableData.find(item => item.id === this.counter_id)
                this.$set(counter, 'remark', this.remark)
                this.$set(counter, 'status', 9)
                this.$set(counter, 'out', dayjs().format('YYYY-MM-DD'))
                this.$message.success('修改成功')
            }
            this.exitVisible = false
        }
    },
    created() {
        Object.assign(this.form, JSON.parse(sessionStorage.getItem('counterList')))
        this.searchCounter()
    }
}
</script>

<style scoped>
.demo-table-expand {
    font-size: 0;
}
.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}
.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 20%;
}
</style>
